package com.xyht.sca_s.student_manage_system.modules.assetConsumable.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonCodeEnum;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonResult;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ExceptionCast;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ResponseResult;
import com.xyht.sca_s.student_manage_system.common.util.CacheUtil;
import com.xyht.sca_s.student_manage_system.modules.asset.entity.CategoryNode;
import com.xyht.sca_s.student_manage_system.modules.asset.entity.SmsAssetCategoryManagement;
import com.xyht.sca_s.student_manage_system.modules.asset.entity.SmsAssetFixedStorage;
import com.xyht.sca_s.student_manage_system.modules.asset.entity.resp.SmsAssetUserResp;
import com.xyht.sca_s.student_manage_system.modules.asset.mapper.SmsAssetCategoryManagementMapper;
import com.xyht.sca_s.student_manage_system.modules.asset.util.AssetUtil;
import com.xyht.sca_s.student_manage_system.modules.asset.util.CategoryUtil;
import com.xyht.sca_s.student_manage_system.modules.assetConsumable.entity.*;
import com.xyht.sca_s.student_manage_system.modules.assetConsumable.entity.req.SmsAssetConsumableStorageBatchReq;
import com.xyht.sca_s.student_manage_system.modules.assetConsumable.entity.req.SmsAssetConsumableStorageDeletedReq;
import com.xyht.sca_s.student_manage_system.modules.assetConsumable.entity.req.SmsAssetConsumableStorageReq;
import com.xyht.sca_s.student_manage_system.modules.assetConsumable.entity.resp.SmsAssetConsumableStorageManageRelationResp;
import com.xyht.sca_s.student_manage_system.modules.assetConsumable.entity.resp.SmsAssetConsumableStorageResp;
import com.xyht.sca_s.student_manage_system.modules.assetConsumable.mapper.*;
import com.xyht.sca_s.student_manage_system.modules.assetConsumable.service.SmsAssetConsumableStorageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyht.sca_s.student_manage_system.modules.assetConsumableBorrow.entity.SmsAssetConsumableBorrowApplyGoods;
import com.xyht.sca_s.student_manage_system.modules.assetConsumableBorrow.mapper.SmsAssetConsumableBorrowApplyGoodsMapper;
import com.xyht.sca_s.student_manage_system.modules.assetConsumableBorrow.mapper.SmsAssetConsumableBorrowApplyMapper;
import com.xyht.sca_s.student_manage_system.modules.assetConsumableOut.entity.SmsAssetConsumableOutStorageApply;
import com.xyht.sca_s.student_manage_system.modules.assetConsumableOut.entity.SmsAssetConsumableOutStorageApplyGoods;
import com.xyht.sca_s.student_manage_system.modules.assetConsumableOut.mapper.SmsAssetConsumableOutStorageApplyGoodsMapper;
import com.xyht.sca_s.student_manage_system.modules.assetConsumableOut.mapper.SmsAssetConsumableOutStorageApplyMapper;
import com.xyht.sca_s.student_manage_system.modules.common.entity.SmsImportTask;
import com.xyht.sca_s.student_manage_system.modules.common.entity.SmsImportTaskDetail;
import com.xyht.sca_s.student_manage_system.modules.common.mapper.SmsImportTaskDetailMapper;
import com.xyht.sca_s.student_manage_system.modules.common.mapper.SmsImportTaskMapper;
import com.xyht.sca_s.student_manage_system.modules.user.entity.SmsUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

import static com.xyht.sca_s.student_manage_system.common.util.ParamCheckUtil.isNullOrEmpty;
import static com.xyht.sca_s.student_manage_system.modules.asset.constant.InStorageMethodConstant.*;
import static com.xyht.sca_s.student_manage_system.modules.assetConsumable.constant.ConsumableStatusConstant.CONSUMABLE_STATUS_IN_STORAGE;
import static com.xyht.sca_s.student_manage_system.modules.common.constant.TaskDetailReason.*;
import static com.xyht.sca_s.student_manage_system.modules.common.constant.TaskDetailReason.REASON_IMPORT_ERR;
import static com.xyht.sca_s.student_manage_system.modules.common.constant.TaskNameExample.TASK_NAME_ASSET_CONSUMABLE_IMPORT;
import static com.xyht.sca_s.student_manage_system.modules.common.constant.TaskStatus.TASK_STATUS_DONE;
import static com.xyht.sca_s.student_manage_system.modules.common.constant.TaskStatus.TASK_STATUS_ERR;
import static com.xyht.sca_s.student_manage_system.modules.common.constant.TaskTypeConstant.TASK_TYPE_ASSET_CONSUMABLE;

/**
 * <p>
 * 易耗品资产库 服务实现类
 * </p>
 *
 * @author XYHT
 * @since 2023-06-27
 */
@Service
public class SmsAssetConsumableStorageServiceImpl extends ServiceImpl<SmsAssetConsumableStorageMapper, SmsAssetConsumableStorage> implements SmsAssetConsumableStorageService {
    @Autowired
    private SmsAssetConsumableStorageMapper smsAssetConsumableStorageMapper;
    @Resource
    private SmsAssetConsumableCategoryManagementMapper smsAssetCategoryManagementMapper;
    @Autowired
    private CacheUtil cacheUtil;
    @Autowired
    private SmsImportTaskMapper smsImportTaskMapper;
    @Autowired
    private AssetUtil assetUtil;
    @Autowired
    private SmsImportTaskDetailMapper smsImportTaskDetailMapper;
    @Resource
    private SmsAssetConsumableStorageManageMapper smsAssetConsumableStorageManageMapper;
    @Resource
    private SmsAssetConsumableStorageManageRelationMapper smsAssetConsumableStorageManageRelationMapper;
    @Resource
    private CategoryUtil categoryUtil;
    @Resource
    private SmsAssetConsumableOutStorageApplyMapper smsAssetConsumableOutStorageApplyMapper;
    @Resource
    private SmsAssetConsumableOutStorageApplyGoodsMapper smsAssetConsumableOutStorageApplyGoodsMapper;
    @Resource
    private SmsAssetConsumableBorrowApplyMapper smsAssetConsumableBorrowApplyMapper;
    @Resource
    private SmsAssetConsumableBorrowApplyGoodsMapper smsAssetConsumableBorrowApplyGoodsMapper;
    @Resource
    private SmsAssetConsumableReturnApplyMapper smsAssetConsumableReturnApplyMapper;
    @Resource
    private SmsAssetConsumableReturnApplyGoodsMapper smsAssetConsumableReturnApplyGoodsMapper;

    @Override
    @Transactional
    public ResponseResult singleAddConsumableStorage(SmsAssetConsumableStorageReq consumableStorageReq, String userId) {
        //校验必填项
        if (isNullOrEmpty(consumableStorageReq.getConsumableName()) || isNullOrEmpty(consumableStorageReq.getConsumableCategory())
                || isNullOrEmpty(consumableStorageReq.getConsumableModel()) || isNullOrEmpty(consumableStorageReq.getConsumableUnit())
                || isNullOrEmpty(consumableStorageReq.getConsumableWarehouseId()) || isNullOrEmpty(consumableStorageReq.getConsumableNum())
                || isNullOrEmpty(consumableStorageReq.getConsumablePrice()) || isNullOrEmpty(consumableStorageReq.getConsumableWarningNum()) ||
                consumableStorageReq.getConsumableNum() <= 0) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        //校验分类是否合法
        SmsAssetConsumableCategoryManagement assetCategoryManagement = smsAssetCategoryManagementMapper.selectById(consumableStorageReq.getConsumableCategory());
        if (assetCategoryManagement == null || isNullOrEmpty(assetCategoryManagement.getId())) {
            return CommonResult.failed(CommonCodeEnum.ASSET_CATEGORY_NOT_EXIST);
        }

        //判断是否为根类别
        if (assetCategoryManagement.getId().length() < 3) {
            return CommonResult.failed(CommonCodeEnum.ASSET_CATEGORY_CAN_NOT_USE_ROOT);
        }

        //校验单价
        if (consumableStorageReq.getConsumablePrice().compareTo(BigDecimal.ZERO) < 0) {
            return CommonResult.failed(CommonCodeEnum.CONSUMABLE_PRICE_ERR);
        }
        //校验仓库
        SmsAssetConsumableStorageManage storageManage = smsAssetConsumableStorageManageMapper.selectById(consumableStorageReq.getConsumableWarehouseId());
        if (isNullOrEmpty(storageManage)) {
            return CommonResult.failed(CommonCodeEnum.STORAGE_MANAGE_NOT_EXIST);
        }
        //创建易耗品资产
        try {
            //设置总价
            Integer consumableNum = consumableStorageReq.getConsumableNum();
            BigDecimal totalPrice = consumableStorageReq.getConsumablePrice().multiply(BigDecimal.valueOf(consumableNum));
            //先查询是否存在该易耗品
            List<SmsAssetConsumableStorage> consumableStorageList = smsAssetConsumableStorageMapper.selectList(new LambdaQueryWrapper<SmsAssetConsumableStorage>()
                    .eq(SmsAssetConsumableStorage::getConsumableName, consumableStorageReq.getConsumableName())
                    .eq(SmsAssetConsumableStorage::getConsumableCategory, consumableStorageReq.getConsumableCategory())
                    .eq(SmsAssetConsumableStorage::getConsumableModel, consumableStorageReq.getConsumableModel())
                    .eq(SmsAssetConsumableStorage::getConsumablePrice, consumableStorageReq.getConsumablePrice())
                    .eq(SmsAssetConsumableStorage::getConsumableUnit, consumableStorageReq.getConsumableUnit()));
            //不存在则信息
            if (consumableStorageList == null || consumableStorageList.size() < 1) {
                //创建易耗品
                SmsAssetConsumableStorage smsAssetConsumableStorage = new SmsAssetConsumableStorage();
                BeanUtils.copyProperties(consumableStorageReq, smsAssetConsumableStorage,"consumableWarehouse_id");
                smsAssetConsumableStorage.setAddUserId(userId);
//                smsAssetConsumableStorage.setConsumableWarehouse(storageManage.getStorageName());
                smsAssetConsumableStorage.setConsumableStatus(CONSUMABLE_STATUS_IN_STORAGE);
                //设置物品id
                String assetId = assetUtil.createAssetStorageID(consumableStorageReq.getConsumableCategory(), new Date(), IN_STORAGE_METHOD_CONSUMABLE_SINGLE, 0);
                smsAssetConsumableStorage.setId(assetId);
//                smsAssetConsumableStorage.setTotalPrice(totalPrice);
                smsAssetConsumableStorageMapper.insert(smsAssetConsumableStorage);
                String consumableStorageId = smsAssetConsumableStorage.getId();
                if (isNullOrEmpty(consumableStorageId)) {
                    return CommonResult.failed(CommonCodeEnum.FAIL);
                }
                //创建该易耗品对应的仓库关系
                SmsAssetConsumableStorageManageRelation relation = new SmsAssetConsumableStorageManageRelation();
                relation.setAssetConsumableId(consumableStorageId);
                relation.setConsumableWarehouseId(consumableStorageReq.getConsumableWarehouseId());
                relation.setConsumableWarehouse(storageManage.getStorageName());
                relation.setConsumableNum(consumableNum);
                relation.setConsumablePrice(consumableStorageReq.getConsumablePrice());
                relation.setTotalPrice(totalPrice);
                relation.setAddUserId(userId);
                smsAssetConsumableStorageManageRelationMapper.insert(relation);
            }else {
                SmsAssetConsumableStorage smsAssetConsumableStorage = consumableStorageList.get(0);
                //如果该物品有仓库则增加数量
                List<SmsAssetConsumableStorageManageRelation> relationList = smsAssetConsumableStorageManageRelationMapper.selectList(new LambdaQueryWrapper<SmsAssetConsumableStorageManageRelation>()
                        .eq(SmsAssetConsumableStorageManageRelation::getAssetConsumableId, smsAssetConsumableStorage.getId())
                        .eq(SmsAssetConsumableStorageManageRelation::getConsumableWarehouseId, consumableStorageReq.getConsumableWarehouseId()));
                if (relationList != null && relationList.size() > 0) {
                    SmsAssetConsumableStorageManageRelation storageManageRelation = relationList.get(0);
                    storageManageRelation.setConsumableNum(storageManageRelation.getConsumableNum() + consumableNum);
                    storageManageRelation.setTotalPrice(totalPrice.add(storageManageRelation.getTotalPrice()));
                    smsAssetConsumableStorageManageRelationMapper.updateById(storageManageRelation);
                }else {
                    //创建该易耗品对应的仓库关系
                    SmsAssetConsumableStorageManageRelation relation = new SmsAssetConsumableStorageManageRelation();
                    relation.setAssetConsumableId(smsAssetConsumableStorage.getId());
                    relation.setConsumableWarehouseId(consumableStorageReq.getConsumableWarehouseId());
                    relation.setConsumableWarehouse(storageManage.getStorageName());
                    relation.setConsumableNum(consumableNum);
                    relation.setConsumablePrice(consumableStorageReq.getConsumablePrice());
                    relation.setTotalPrice(totalPrice);
                    relation.setAddUserId(userId);
                    relation.setRemark(consumableStorageReq.getRemark());
                    smsAssetConsumableStorageManageRelationMapper.insert(relation);
                }
            }

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.FAIL));
        }
        return CommonResult.success();
    }

    @Override
    public ResponseResult getConsumableStorage(Integer pageNum, Integer pageSize, String searchStr, String consumableCategory, String consumableWarehouseId) {
        Page<SmsAssetConsumableStorage> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<SmsAssetConsumableStorage> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (!isNullOrEmpty(consumableCategory) && !consumableCategory.equals("0")) {
            SmsAssetConsumableCategoryManagement originCategory = smsAssetCategoryManagementMapper.selectById(consumableCategory);
            if (originCategory == null) {
                return CommonResult.failed(CommonCodeEnum.ASSET_CATEGORY_NOT_EXIST);
            }
            CategoryNode originCategoryNode = new CategoryNode();
            BeanUtils.copyProperties(originCategory, originCategoryNode);

            List<CategoryNode> categoryList =
                    smsAssetCategoryManagementMapper.selectList(new QueryWrapper<>())
                            .stream()
                            .map(category -> {
                                CategoryNode categoryNode = new CategoryNode();
                                BeanUtils.copyProperties(category, categoryNode);
                                return categoryNode;
                            })
                            .collect(Collectors.toList());

            CategoryNode resultCategory = categoryUtil.getChildrenNode(originCategoryNode, categoryList);
            List<String> childrenList = new ArrayList<>();
            childrenList = categoryUtil.getChildrenIDList(resultCategory, childrenList);
            childrenList.add(resultCategory.getId());
            lambdaQueryWrapper.in(SmsAssetConsumableStorage::getConsumableCategory, childrenList);
        }
        if (!isNullOrEmpty(consumableWarehouseId)) {
            List<String> consumableWarehouseIdList = smsAssetConsumableStorageManageRelationMapper.selectList(new LambdaQueryWrapper<SmsAssetConsumableStorageManageRelation>()
                            .eq(SmsAssetConsumableStorageManageRelation::getConsumableWarehouseId, consumableWarehouseId))
                    .stream()
                    .map(SmsAssetConsumableStorageManageRelation::getAssetConsumableId)
                    .collect(Collectors.toList());
            if (consumableWarehouseIdList.isEmpty()) {
                lambdaQueryWrapper.eq(SmsAssetConsumableStorage::getId, "");
            }else {
                lambdaQueryWrapper.in(SmsAssetConsumableStorage::getId, consumableWarehouseIdList);
            }
        }
        if (!isNullOrEmpty(searchStr)) {
            lambdaQueryWrapper.and(lambdaQuery ->
                    lambdaQuery.like(SmsAssetConsumableStorage::getConsumableName, searchStr)
                            .or()
                            .like(SmsAssetConsumableStorage::getConsumablePrice, searchStr)
                            .or()
                            .like(SmsAssetConsumableStorage::getConsumableModel, searchStr));
        }

        lambdaQueryWrapper.orderByAsc(SmsAssetConsumableStorage::getConsumableStatus).orderByDesc(SmsAssetConsumableStorage::getCreateTime);

        smsAssetConsumableStorageMapper.selectPage(page, lambdaQueryWrapper);

        List<SmsAssetConsumableStorageResp> list = page.getRecords().stream().map(consumable -> {
            SmsAssetConsumableStorageResp consumableStorageResp = new SmsAssetConsumableStorageResp();
            BeanUtils.copyProperties(consumable, consumableStorageResp);
            //总数量
            int sum = smsAssetConsumableStorageManageRelationMapper.selectList(new LambdaQueryWrapper<SmsAssetConsumableStorageManageRelation>()
                            .eq(SmsAssetConsumableStorageManageRelation::getAssetConsumableId, consumable.getId()))
                    .stream()
                    .mapToInt(SmsAssetConsumableStorageManageRelation::getConsumableNum)
                    .sum();
            consumableStorageResp.setConsumableSumNum(sum);
            //设置分类名称
            SmsAssetConsumableCategoryManagement categoryManagement = smsAssetCategoryManagementMapper.selectById(consumable.getConsumableCategory());
            if (categoryManagement != null) {
                consumableStorageResp.setConsumableCategoryName(categoryManagement.getCategoryName());
            }

            SmsUser smsUser = cacheUtil.getUserInfo(consumable.getAddUserId());
            if (smsUser != null) {
                SmsAssetUserResp smsAssetUserResp = new SmsAssetUserResp();
                BeanUtils.copyProperties(smsUser, smsAssetUserResp);
                consumableStorageResp.setUserInfo(smsAssetUserResp);
            }
            List<SmsAssetConsumableStorageManageRelationResp> warehouseInfList = smsAssetConsumableStorageManageRelationMapper.selectList(new LambdaQueryWrapper<SmsAssetConsumableStorageManageRelation>()
                    .eq(SmsAssetConsumableStorageManageRelation::getAssetConsumableId, consumable.getId()))
                    .stream()
                    .map(relation -> {
                        SmsAssetConsumableStorageManageRelationResp relationResp = new SmsAssetConsumableStorageManageRelationResp();
                        BeanUtils.copyProperties(relation, relationResp);
                        return relationResp;
                    })
                    .collect(Collectors.toList());
            consumableStorageResp.setWarehouseInfList(warehouseInfList);
            return consumableStorageResp;
        }).collect(Collectors.toList());

        int total = (int) page.getTotal();
        return CommonResult.success(list, total);
    }

    @Override
    public ResponseResult getConsumableStorageById(String assetId) {
        SmsAssetConsumableStorage consumable = smsAssetConsumableStorageMapper.selectById(assetId);
        if (consumable == null){
            return CommonResult.failed(CommonCodeEnum.CONSUMABLE_NOT_EXIST);
        }

        SmsAssetConsumableStorageResp consumableStorageResp = new SmsAssetConsumableStorageResp();
        BeanUtils.copyProperties(consumable, consumableStorageResp);
        //总数量
        int sum = smsAssetConsumableStorageManageRelationMapper.selectList(new LambdaQueryWrapper<SmsAssetConsumableStorageManageRelation>()
                .eq(SmsAssetConsumableStorageManageRelation::getAssetConsumableId, consumable.getId()))
                .stream()
                .mapToInt(SmsAssetConsumableStorageManageRelation::getConsumableNum)
                .sum();
        consumableStorageResp.setConsumableSumNum(sum);
        //设置分类名称
        SmsAssetConsumableCategoryManagement categoryManagement = smsAssetCategoryManagementMapper.selectById(consumable.getConsumableCategory());
        if (categoryManagement != null) {
            consumableStorageResp.setConsumableCategoryName(categoryManagement.getCategoryName());
        }

        SmsUser smsUser = cacheUtil.getUserInfo(consumable.getAddUserId());
        if (smsUser != null) {
            SmsAssetUserResp smsAssetUserResp = new SmsAssetUserResp();
            BeanUtils.copyProperties(smsUser, smsAssetUserResp);
            consumableStorageResp.setUserInfo(smsAssetUserResp);
        }
        List<SmsAssetConsumableStorageManageRelationResp> warehouseInfList = smsAssetConsumableStorageManageRelationMapper.selectList(new LambdaQueryWrapper<SmsAssetConsumableStorageManageRelation>()
                .eq(SmsAssetConsumableStorageManageRelation::getAssetConsumableId, consumable.getId()))
                .stream()
                .map(relation -> {
                    SmsAssetConsumableStorageManageRelationResp relationResp = new SmsAssetConsumableStorageManageRelationResp();
                    BeanUtils.copyProperties(relation, relationResp);
                    return relationResp;
                })
                .collect(Collectors.toList());
        consumableStorageResp.setWarehouseInfList(warehouseInfList);
        return CommonResult.success(consumableStorageResp);
    }

    @Override
    @Async
    public Future<ResponseResult> batchAddConsumableStorage(Map<String, Object> map, String userId) {
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(map));
        List<SmsAssetConsumableStorageBatchReq> consumableStorageList = JSONObject.parseArray(JSON.toJSONString(jsonObject.get("list")), SmsAssetConsumableStorageBatchReq.class);
        if (consumableStorageList == null || consumableStorageList.size() < 1) {
            return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.INVALID_PARAM));
        }
        //创建导入任务
        SmsImportTask smsImportTask = new SmsImportTask();
        smsImportTask.setTaskName(TASK_NAME_ASSET_CONSUMABLE_IMPORT);
        smsImportTask.setUserId(userId);
        smsImportTask.setTaskType(TASK_TYPE_ASSET_CONSUMABLE);
        smsImportTaskMapper.insert(smsImportTask);

        batchAddFixedStorage(consumableStorageList, smsImportTask.getId(), userId);

        return new AsyncResult<>(CommonResult.success());
    }

    @Override
    public ResponseResult bathDeletedConsumableStorage(SmsAssetConsumableStorageDeletedReq deletedReq) {
        if (deletedReq.getDeletedIdList() == null || deletedReq.getDeletedIdList().size() < 1) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        //校验是否提交了申请
//        //出库
//        List<String> applyIdList = smsAssetConsumableOutStorageApplyGoodsMapper.selectList(new LambdaQueryWrapper<SmsAssetConsumableOutStorageApplyGoods>()
//                        .in(SmsAssetConsumableOutStorageApplyGoods::getAssetConsumableId, deletedReq.getDeletedIdList()))
//                .stream()
//                .map(SmsAssetConsumableOutStorageApplyGoods::getApplyId)
//                .collect(Collectors.toList());
//
//        //领用
//        smsAssetConsumableBorrowApplyGoodsMapper.
//        //归还
//        smsAssetConsumableReturnApplyGoodsMapper
        smsAssetConsumableStorageMapper.deleteBatchIds(deletedReq.getDeletedIdList());
        return CommonResult.success();
    }

    @Resource
    PlatformTransactionManager transactionManager;

    private void batchAddFixedStorage(List<SmsAssetConsumableStorageBatchReq> consumableStorageListReq, String taskId, String userId) {
        int OFFSET_ROW = 2;
        Date nowDate = new Date();
        Integer task_finish_status = TASK_STATUS_DONE;

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = simpleDateFormat.format(nowDate);

        //获取当天批次
        Integer count = smsImportTaskMapper.selectCount(new LambdaQueryWrapper<SmsImportTask>().like(SmsImportTask::getCreateTime, dateStr));

        for (int i = 0; i < consumableStorageListReq.size(); i++) {
            //开启事务
            DefaultTransactionDefinition dt = new DefaultTransactionDefinition();
            //嵌套事务 PROPAGATION_REQUIRES_NEW 每次开启一个新的事务
            dt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
            //设置嵌套事务
            TransactionStatus status = transactionManager.getTransaction(dt);

            //校验当前物品必填项是否填写完毕
            SmsAssetConsumableStorageBatchReq storage = consumableStorageListReq.get(i);
            if (isNullOrEmpty(storage.getConsumableUnit()) || isNullOrEmpty(storage.getConsumableCategoryName())
                    || isNullOrEmpty(storage.getConsumableWarehouse())
                    || isNullOrEmpty(storage.getConsumableModel()) || isNullOrEmpty(storage.getConsumableName())
                    || isNullOrEmpty(storage.getConsumableNum()) || isNullOrEmpty(storage.getConsumablePrice())) {
                transactionManager.rollback(status);
                task_finish_status = TASK_STATUS_ERR;
                createTeacherImportTaskDetail(taskId, REASON_INVALID_PARAM, String.valueOf(i + OFFSET_ROW));
                continue;
            }

            //校验分类是否存在
            SmsAssetConsumableCategoryManagement categoryManagement =
                    smsAssetCategoryManagementMapper.selectOne(new LambdaQueryWrapper<SmsAssetConsumableCategoryManagement>()
                            .eq(SmsAssetConsumableCategoryManagement::getCategoryName, storage.getConsumableCategoryName()));
            if (categoryManagement == null || isNullOrEmpty(categoryManagement.getId())) {
                transactionManager.rollback(status);
                task_finish_status = TASK_STATUS_ERR;
                createTeacherImportTaskDetail(taskId, REASON_ASSET_CATEGORY_NOT_EXIST, String.valueOf(i + OFFSET_ROW));
                continue;
            }

            //判断是否为根类别
            if (categoryManagement.getId().length() < 3) {
                transactionManager.rollback(status);
                task_finish_status = TASK_STATUS_ERR;
                createTeacherImportTaskDetail(taskId, REASON_ASSET_CATEGORY_CAN_NOT_USE_ROOT, String.valueOf(i + OFFSET_ROW));
                continue;
            }

            //判断数量
            if (storage.getConsumableNum().equals(0)) {
                transactionManager.rollback(status);
                task_finish_status = TASK_STATUS_ERR;
                createTeacherImportTaskDetail(taskId, REASON_ASSET_NUM_ERR, String.valueOf(i + OFFSET_ROW));
                continue;
            }

            //校验单价
            if (storage.getConsumablePrice().compareTo(BigDecimal.ZERO) < 0) {
                transactionManager.rollback(status);
                task_finish_status = TASK_STATUS_ERR;
                createTeacherImportTaskDetail(taskId, REASON_ASSET_PRICE_ERR, String.valueOf(i + OFFSET_ROW));
                continue;
            }

            //校验仓库
            SmsAssetConsumableStorageManage storageManage = smsAssetConsumableStorageManageMapper.selectOne(new LambdaQueryWrapper<SmsAssetConsumableStorageManage>()
                    .eq(SmsAssetConsumableStorageManage::getStorageName,storage.getConsumableWarehouse()));
            if (isNullOrEmpty(storageManage)) {
                transactionManager.rollback(status);
                task_finish_status = TASK_STATUS_ERR;
                createTeacherImportTaskDetail(taskId, REASON_STORAGE_MANAGE_NOT_EXIST, String.valueOf(i + OFFSET_ROW));
                continue;
            }

            //易耗品入库
            try {

                //设置总价
                Integer consumableNum = storage.getConsumableNum();
                BigDecimal totalPrice = storage.getConsumablePrice().multiply(BigDecimal.valueOf(consumableNum));
                //先查询是否存在该易耗品
                List<SmsAssetConsumableStorage> consumableStorageList = smsAssetConsumableStorageMapper.selectList(new LambdaQueryWrapper<SmsAssetConsumableStorage>()
                        .eq(SmsAssetConsumableStorage::getConsumableName, storage.getConsumableName())
                        .eq(SmsAssetConsumableStorage::getConsumableCategory, categoryManagement.getId())
                        .eq(SmsAssetConsumableStorage::getConsumableModel, storage.getConsumableModel())
                        .eq(SmsAssetConsumableStorage::getConsumablePrice, storage.getConsumablePrice())
                        .eq(SmsAssetConsumableStorage::getConsumableUnit, storage.getConsumableUnit()));
                //不存在则信息
                if (consumableStorageList == null || consumableStorageList.size() < 1) {
                    //创建易耗品
                    SmsAssetConsumableStorage smsAssetConsumableStorage = new SmsAssetConsumableStorage();
                    BeanUtils.copyProperties(storage, smsAssetConsumableStorage,"consumableWarehouse_id");
                    smsAssetConsumableStorage.setAddUserId(userId);
//                smsAssetConsumableStorage.setConsumableWarehouse(storageManage.getStorageName());
                    smsAssetConsumableStorage.setConsumableStatus(CONSUMABLE_STATUS_IN_STORAGE);
                    smsAssetConsumableStorage.setConsumableWarehouseId(storageManage.getId());
                    smsAssetConsumableStorage.setConsumableCategory(categoryManagement.getId());
                    //设置物品id
                    String assetId = assetUtil.createAssetStorageID(categoryManagement.getId(), new Date(), IN_STORAGE_METHOD_CONSUMABLE_IMPORT, count + 1);
                    smsAssetConsumableStorage.setId(assetId);
//                smsAssetConsumableStorage.setTotalPrice(totalPrice);
                    smsAssetConsumableStorageMapper.insert(smsAssetConsumableStorage);
                    String consumableStorageId = smsAssetConsumableStorage.getId();
                    if (isNullOrEmpty(consumableStorageId)) {
                        transactionManager.rollback(status);
                        task_finish_status = TASK_STATUS_ERR;
                        createTeacherImportTaskDetail(taskId, REASON_FAIL, String.valueOf(i + OFFSET_ROW));
                    }
                    //创建该易耗品对应的仓库关系
                    SmsAssetConsumableStorageManageRelation relation = new SmsAssetConsumableStorageManageRelation();
                    relation.setAssetConsumableId(consumableStorageId);
                    relation.setConsumableWarehouseId(storageManage.getId());
                    relation.setConsumableWarehouse(storageManage.getStorageName());
                    relation.setConsumableNum(consumableNum);
                    relation.setConsumablePrice(storage.getConsumablePrice());
                    relation.setTotalPrice(totalPrice);
                    relation.setAddUserId(userId);
                    smsAssetConsumableStorageManageRelationMapper.insert(relation);
                }else {
                    SmsAssetConsumableStorage smsAssetConsumableStorage = consumableStorageList.get(0);
                    //创建该易耗品对应的仓库关系
                    SmsAssetConsumableStorageManageRelation relation = new SmsAssetConsumableStorageManageRelation();
                    relation.setAssetConsumableId(smsAssetConsumableStorage.getId());
                    relation.setConsumableWarehouseId(storageManage.getId());
                    relation.setConsumableWarehouse(storageManage.getStorageName());
                    relation.setConsumableNum(consumableNum);
                    relation.setConsumablePrice(storage.getConsumablePrice());
                    relation.setTotalPrice(totalPrice);
                    relation.setAddUserId(userId);
                    relation.setRemark(storage.getRemark());
                    smsAssetConsumableStorageManageRelationMapper.insert(relation);
                }


                transactionManager.commit(status);
            } catch (Exception e) {
                transactionManager.rollback(status);
                task_finish_status = TASK_STATUS_ERR;
                createTeacherImportTaskDetail(taskId, REASON_IMPORT_ERR, String.valueOf(i + OFFSET_ROW));
            }
        }
        SmsImportTask smsImportTask = new SmsImportTask();
        smsImportTask.setId(taskId);
        smsImportTask.setStatus(task_finish_status);
        smsImportTaskMapper.updateById(smsImportTask);
    }

    private void createTeacherImportTaskDetail(String taskId, String reason, String row) {
        SmsImportTaskDetail smsImportTaskDetail = new SmsImportTaskDetail();
        smsImportTaskDetail.setTaskId(taskId);
        smsImportTaskDetail.setFailReason(reason);
        smsImportTaskDetail.setFailRow(row);
        smsImportTaskDetailMapper.insert(smsImportTaskDetail);
    }
}
